<template>
  <div style="padding: 20px">
    <div
      style="
        height: 50px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px 0 20px;
      "
    >
      <!-- 搜索框 -->
      <div>
        <el-space :size="60">
          <el-input
            v-model="machineId"
            style="width: 240px"
            size="large"
            placeholder="输入机器编号"
            clearable
            @clear="machineIdClear"
          >
            <template #append>
              <el-button @click="searchWithMachineId" :icon="Search" />
            </template>
          </el-input>

          <el-input
            v-model="location"
            style="width: 240px"
            size="large"
            placeholder="输入机器部署位置"
            clearable
            @clear="locationClear"
          >
            <template #append>
              <el-button @click="searchWithLocation" :icon="Search" />
            </template>
          </el-input>
        </el-space>
      </div>

      <!-- 右侧新增按钮 -->
      <div style="display: flex">
        <el-upload
          style="margin-right: 13px"
          class="upload-demo"
          action="http://localhost:9600/common/import"
          accept=".xlsx"
          :on-success="handleExcelImportSuccess"
        >
          <el-button type="success"
            ><el-icon style="margin-right: 5px"><Download /></el-icon
            >导入</el-button
          >
        </el-upload>

        <el-button type="warning" @click="handleExport"
          ><el-icon style="margin-right: 5px"><Upload /></el-icon
          >导出</el-button
        >
        <el-button @click="addMachine" type="primary"
          ><el-icon style="margin-right: 5px"><Plus /></el-icon>添加</el-button
        >
      </div>
    </div>

    <!-- 表格数据展示部分 -->
    <div style="padding: 20px">
      <el-table
        show-overflow-tooltip="true"
        :data="tableData"
        style="width: 100%"
        height="auto"
        v-loading="dataLoading"
        element-loading-text="数据加载中..."
      >
        <el-table-column fixed prop="machineId" label="编号" width="240" />
        <el-table-column prop="manufacturer" label="厂商" width="140" />
        <el-table-column prop="location" label="部署位置" width="140" />
        <el-table-column prop="status" label="机器状态" width="130">
          <template #default="scope">
            <el-tag
              style="font-size: 13px"
              v-if="scope.row.status === '激活'"
              type="success"
              size="large"
              effect="dark"
              >{{ scope.row.status }}</el-tag
            >
            <el-tag
              style="font-size: 13px"
              v-if="scope.row.status === '停用'"
              type="danger"
              size="large"
              effect="dark"
              >{{ scope.row.status }}</el-tag
            >
            <el-tag
              style="font-size: 13px"
              v-if="scope.row.status === '故障'"
              type="warning"
              size="large"
              effect="dark"
              >{{ scope.row.status }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="status" label="代办任务" width="130">
          <template #default="scope">
            <el-tag
              style="font-size: 13px"
              v-if="scope.row.waitTask === 0"
              type="success"
              size="large"
              effect="dark"
              >无</el-tag
            >
            <el-tag
              style="font-size: 13px"
              v-if="scope.row.waitTask !== 0"
              type="success"
              size="large"
              effect="dark"
              >{{ scope.row.waitTask }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="投入时间" width="220" />
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click.prevent="echoMachine(scope.row.id)"
            >
              修改
            </el-button>

            <el-popconfirm
              cancel-button-text="取消"
              confirm-button-text="确认"
              title="确认删除?"
              @confirm="deleteMachine(scope.row.id)"
              icon="Warning"
            >
              <template #reference>
                <el-button link type="danger" size="small"> 删除 </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div style="padding: 10px 0 20px 20px">
      <el-pagination
        :current-page="pageNO"
        :page-size="pageSize"
        background
        @change="handlePageChange"
        layout="prev, pager, next"
        :total="total"
      />
    </div>
  </div>

  <!-- 表单收集机器数据 -->
  <el-drawer
    ref="drawerRef"
    v-model="dialog"
    title="添加机器"
    direction="rtl"
    class="demo-drawer"
    size="340px"
    @close="hanleClose"
  >
    <div class="demo-drawer__content">
      <el-form ref="ruleFormRef" :rules="rules" :model="machine">
        <el-form-item prop="machineId" label="编号">
          <el-input
            placeholder="长度6~18位"
            v-model="machine.machineId"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item prop="manufacturer" label="厂商">
          <el-input v-model="machine.manufacturer" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="location" label="位置">
          <!-- <el-input v-model="machine.location" autocomplete="off" /> -->
          <el-autocomplete
            style="width: 100%"
            size="large"
            v-model="machine.location"
            :fetch-suggestions="querySearchAsync"
            placeholder="输入部署城市名称"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-select v-model="machine.status" placeholder="选择机器状态">
            <el-option label="停用" value="停用" />
            <el-option label="激活" value="激活" />
            <el-option label="故障" value="故障" />
          </el-select>
        </el-form-item>
      </el-form>

      <div style="margin-top: 40px; display: flex; justify-content: end">
        <el-button @click="hanleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="doSubmit"
          >提交</el-button
        >
      </div>
    </div>

    <template #header>
      <h4 style="color: #000000">添加机器</h4>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Search } from "@element-plus/icons-vue";
import { ElDrawer, ElMessage } from "element-plus";
import {
  saveMachine,
  queryWithMachineId,
  queryWithLocation,
  removeMachine,
  findMachineEcho,
  updateMachine,
} from "@/api/machine/index";
import { queryLocationData } from "@/api/location/index";

const dataLoading = ref(true);
const tableData = ref([]);
const pageNo = ref(1);
const pageSize = ref(10);
const total = ref(0);
const machineId = ref(null);
const location = ref(null);
onMounted(() => {
  getMachineList();
});

//获取分页数据
const getMachineList = () => {
  queryWithMachineId(pageNo.value, pageSize.value, machineId.value).then(
    (res) => {
      if (res.code === 200 && res.data !== null) {
        tableData.value = res.data.data;
        total.value = res.data.total;
        dataLoading.value = false;
      } else {
        dataLoading.value = false;
      }
    }
  );
};

//监听分页
const handlePageChange = (currentNO, currentSize) => {
  pageNo.value = currentNO;
  pageSize.value = currentSize;
  getMachineList();
};

//机器实体类
const machine = ref({
  id: null,
  machineId: null,
  manufacturer: null,
  location: "",
  status: null,
});

//重新加载函数
const setMachine = () => {
  loading.value = false;
  dialog.value = false;
  machine.value = {};
  //重新刷新页面
  window.location.reload();
};

//表单校验
const ruleFormRef = ref();
const rules = ref({
  machineId: [
    { required: true, message: "请输入机器编号", trigger: "blur" },
    { min: 6, max: 18, message: "长度6~18位", trigger: "blur" },
  ],
  manufacturer: [
    {
      required: true,
      message: "请输入机器厂商",
      trigger: "change",
    },
  ],
  location: [
    {
      required: true,
      message: "请输入机器部署位置",
      trigger: "change",
    },
  ],
  status: [
    {
      required: true,
      message: "请输入机器当前状态",
      trigger: "change",
    },
  ],
});

const dialog = ref(false);
const loading = ref(false);
//添加弹框
const addMachine = () => {
  dialog.value = true;
};

let timeout = null;
function querySearchAsync(name, callback) {
  queryLocationData().then((res) => {
    if (res.code === 200) {
      const list = [];
      //封装要显示的数据
      for (let v of res.data) {
        list.push({ value: v });
      }
      const results = name ? list.filter(createFilter(name)) : list;
      // 调用 callback 返回建议列表的数据,是一个数组类型
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        callback(results);
      }, 2000 * Math.random());
    }
  });
}

const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

//搜索方法
const handleSelect = (param) => {
  machine.value.location = param.value;
};

//提交表单
const doSubmit = () => {
  ruleFormRef.value
    .validate()
    .then(() => {
      loading.value = true;
      if (machine.value.id === null) {
        saveMachine(machine.value).then((res) => {
          if (res.code == 200) {
            ElMessage({
              showClose: true,
              message: "添加成功！",
              center: true,
              type: "success",
            });
            setMachine();
          } else {
            setMachine();
          }
        });
      } else {
        //修改
        updateMachine(machine.value).then((res) => {
          if (res.code == 200) {
            ElMessage({
              showClose: true,
              message: "修改成功！",
              center: true,
              type: "success",
            });
            setMachine();
          } else {
            setMachine();
          }
        });
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};

//根据编号搜索
const searchWithMachineId = () => {
  getMachineList();
};

//根据位置搜索
const doSearchWithLocation = () => {
  queryWithLocation(pageNo.value, pageSize.value, location.value).then(
    (res) => {
      if (res.code === 200 && res.data !== null) {
        tableData.value = res.data.data;
        total.value = res.data.total;
        dataLoading.value = false;
      }
    }
  );
};
const searchWithLocation = () => {
  doSearchWithLocation();
};

//取消按钮
const hanleClose = () => {
  loading.value = false;
  dialog.value = false;
  machine.value = {};
};

//清除按钮
const machineIdClear = () => {
  getMachineList();
};

//清除按钮
const locationClear = () => {
  doSearchWithLocation();
};

//删除功能
const deleteMachine = (id) => {
  removeMachine(id).then((res) => {
    if (res.code === 200) {
      getMachineList();
      ElMessage({
        showClose: true,
        message: "删除成功！",
        center: true,
        type: "success",
      });
    }
  });
};

//回显数据
const echoMachine = (id) => {
  findMachineEcho(id).then((res) => {
    if (res.code === 200) {
      machine.value = res.data;
      dialog.value = true;
    }
  });
};

//导出数据
const handleExport = () => {
  window.open("http://localhost:9600/common/export");
  ElMessage({
    showClose: true,
    message: "导出成功！",
    type: "success",
  });
};

//机器数据导入
function handleExcelImportSuccess() {
  ElMessage({
    showClose: true,
    message: "导入成功！",
    type: "success",
  });
  //重新刷新页面
  window.location.reload();
}
</script>

<style scoped>
</style>